package com.heima.article.service.impl;

import com.heima.article.service.collectionBehaviorService;
import com.heima.model.article.dtos.CollectionBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author rookie001
 * @creat 2023-06-21-10:37
 */
@Service
public class collectionBehaviorServiceImpl implements collectionBehaviorService {
    @Autowired
    private RedisTemplate redisTemplate;

    //文章收藏
    @Override
    public ResponseResult collectionBehavior(CollectionBehaviorDto dto) {
        //数据校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //获取用户id
        Integer id = AppThreadLocalUtils.getUser().getId();
        //判断用户是否登录
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.TOKEN_EXPIRE);
        }
        //设置收藏key
        String key = id + dto.getArticleId() + "collection";
        String collection = (String) redisTemplate.opsForValue().get(key);
        if (collection == null) {
            //若为空添加
            redisTemplate.opsForValue().set(key, dto.getType() + "");
        } else {
            if (collection.equals("1")) {
                redisTemplate.delete(key);
            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
